import React, { useState, useEffect, useMemo, useRef } from 'react';
import { AutoComplete } from 'antd';
import { debounce } from 'lodash';
import PropTypes from 'prop-types';
import { useDebounceEffect } from 'ahooks';

function findLabel(options, value) {
  const item = options?.find((op) => op.value === value);
  // console.log('findLabel', value, options, item ? item?.label : value);
  return item ? item?.label : value;
}
function findValue(options, initValue) {
  const item = options?.find((op) => op.title === initValue);
  // console.log('findValue', item ? item?.value : initValue);
  return item ? item?.value : initValue;
}
const AutoCompleteC = ({
  initialValue,
  value: originValue,
  options,
  onChange = () => {},
  placeholder,
  onSearch,
  onSelect: handleSelect,
  style,
  children,
  allowClear,
  disabled,
}) => {
  // useEffect(() => {
  //   if (initialValue) {
  //     setNewValue(originValue);
  //   }
  // }, [originValue, initialValue]);
  // 定义了state变量 newValue
  // 使用 setNewValue 方法更新newValue
  // 初始值是从父容器传入的 value
  // 如果初始值为唯一ID，则newValue值为对应的label，若不是唯一ID，则newValue是直接文本
  const [newValue, setNewValue] = useState(() => {
    return findLabel(options, initialValue ? initialValue : originValue);
  });
  // 响应value或options值的变更，当变更时，更新newValue
  useDebounceEffect(
    () => {
      if (initialValue) {
        setNewValue(findLabel(options, initialValue));
        onSelect(null, { key: findValue(options, initialValue) });
        // console.log('initialValue', originValue);
      }
      if (!initialValue) {
        // console.log('!initialValue', originValue, newValue, options);
        setNewValue(findLabel(options, originValue));
      }
    },
    [options, initialValue, originValue],
    { wait: 500 },
  );

  // 当options变更时，重新更新newOptions
  const newOptions = useMemo(() => {
    return options?.map((op) => {
      const { value, label } = op;
      return {
        key: value,
        value: label,
      };
    });
  }, [options]);

  const throttleHandleChange = debounce(onChange, 20);

  const handleChange = (value) => {
    // console.log('handleChange', value);
    throttleHandleChange(value);
    setNewValue(value);
  };

  const onSelect = (val, option) => {
    // console.log('onSelect', newOptions, option);
    throttleHandleChange(option.key);
    if (typeof handleSelect === 'function') {
      handleSelect(option.key);
    }
  };
  return (
    <AutoComplete
      allowClear={allowClear}
      style={style}
      options={
        options && options.length > 0
          ? newOptions
          : options === undefined
          ? [{ label: <span disabled={true}>正在加载中....</span> }]
          : [{ label: <span disabled={true}>无匹配的结果</span> }]
      }
      // options={newOptions}
      placeholder={placeholder}
      value={newValue}
      disabled={disabled}
      onChange={handleChange}
      onSelect={onSelect}
      // filterOption={(inputValue, option) => option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
      onSearch={onSearch}
    >
      {children}
    </AutoComplete>
  );
};
AutoCompleteC.propsTypes = {
  options: PropTypes.array, // 下拉数据
  onChange: PropTypes.func, // change事件
  placeholder: PropTypes.string, // 灰色的输入提示
  onSearch: PropTypes.func, // 搜索事件
  handleSelect: PropTypes.func, // 选中事件
  style: PropTypes.object, // 额外样式
  children: PropTypes.element, // 子元素
  allowClear: PropTypes.bool, // 允许清除
  disabled: PropTypes.bool, // 是否禁用
};
export default AutoCompleteC;
